﻿using Microsoft.TeamFoundation.Build.Client;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TFSUtilLibrary.Model;

namespace TFSUtilLibrary
{
    public class Builds
    {
        public static List<WorkItemData> GetAssociatedWorkItems(string tfsURI, string project, string buildName, string sourceBranch, string targetBranch)
        {
            List<WorkItem> allWorkItems = new List<WorkItem>();
            
            Connection con = new Connection(tfsURI);
            if (!con.ConnectToTFS())
                Common.Messages.ThrowNonConnect();

            var buildServer = con.BuildServer;

            IBuildDefinition buildDef = buildServer.GetBuildDefinition(project, buildName);
            IOrderedEnumerable<IBuildDetail> builds = buildServer.QueryBuilds(buildDef).OrderByDescending(build => build.LastChangedOn);

            if (builds.Count() < 2)
                return null;

            IBuildDetail newestBuild = builds.ElementAt(0);            
            IBuildDetail priorBuild = builds.ElementAt(1);

            var newChangesets = newestBuild.Information.GetNodesByType("AssociatedChangeset");
            string newestBuildChangesetId = newChangesets[0].Fields["ChangesetId"];

            var priorChangesets = priorBuild.Information.GetNodesByType("AssociatedChangeset");
            string priorBuildChangesetId = priorChangesets[0].Fields["ChangesetId"];

            VersionControlServer vcs = con.VCS;
            VersionSpec versionFrom = VersionSpec.ParseSingleSpec(newestBuildChangesetId, null);
            VersionSpec versionTo = VersionSpec.ParseSingleSpec(priorBuildChangesetId, null);

            ChangesetMergeDetails results = vcs.QueryMergesWithDetails(sourceBranch, VersionSpec.Latest, 0, targetBranch, VersionSpec.Latest, 0, versionFrom, versionTo, RecursionType.Full);
            foreach (Changeset change in results.Changesets)
            {
                Changeset details = vcs.GetChangeset(change.ChangesetId);
                allWorkItems.AddRange(details.WorkItems);
            }

            return allWorkItems.Select(wi => new WorkItemData() { WorkItemNumber = wi.Id, WorkItemDescription = wi.Title }).ToList();
        }
    }
}
